package com.blockchain.securewallet.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;
import com.blockchain.securewallet.base.BaseActivity;
import com.blockchain.securewallet.dialog.IDialogListener;
import com.blockchain.securewallet.dialog.UniversalDialog;
import com.blockchain.securewallet.manager.ThreadPoolManager;
import com.blockchain.securewallet.model.db.CoinWallet;
import com.blockchain.securewallet.tools.LZW;
import com.blockchain.securewallet.tools.WeakHandler;
import com.blockchain.securewallet.utils.Logger;
import com.blockchain.securewallet.utils.StringUtil;
import com.blockchain.securewallet.utils.ToastUtils;
import com.blockchain.securewallet.utils.ToolUtils;
import com.blockchain.securewallet.utils.UIHelper;

import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

public class TransactionActivity extends BaseActivity implements IDialogListener {

    public static final String KEY_WALLET_ID = "wallet_id";
    public static final String KEY_TRANSACTION = "transaction";

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.iv_qr_code)
    ImageView ivQrCode;

    @BindView(R.id.iv_qr_sub)
    ImageView iv_qr_sub;

    @BindView(R.id.iv_qr_add)
    ImageView iv_qr_add;

    @BindView(R.id.tv_page_index)
    TextView tvIndex;

    @BindView(R.id.tv_last_page)
    TextView tv_last_page;

    @BindView(R.id.tv_next_page)
    TextView tv_next_page;

    @BindView(R.id.cv_qr_code)
    ConstraintLayout cvQrCode;

    @BindView(R.id.iv_page_up)
    ImageView ivPageUp;

    @BindView(R.id.iv_page_down)
    ImageView ivPageDown;


    //一页500字节(Byte)这样
    private final int BYTE_PER_PAGE = 500;

    private int walletId;
    private CoinWallet wallet;

    private int index;
    private int total;
    private int infoSize;

    private Bitmap[] bitmaps;

    //对交易数据的数字签名
    private String transaction = "";
    //对地址、币种、交易签名Json的二维码压缩数据
    private String transactionEncode = "";

    private boolean isOk;
    private String current = "0%";
    //第一次要快速显示二维码
    private boolean isFirst;

    //手指按下位置的横坐标
    private float StartX;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transaction);
        ButterKnife.bind(this);
        tvTitle.setText(R.string.generate_transaction);

        Intent intent = getIntent();
        if (intent != null) {
            walletId = intent.getIntExtra(KEY_WALLET_ID, 0);
            transaction = intent.getStringExtra(KEY_TRANSACTION);

            Logger.ds("TransactionActivity 传递过来的签名: " + transaction);
//            if(wallet.getType()==CoinWallet.TYPE_BIT_COIN) {
//                transaction = "01000000000101523312544fd94beeeb4a08127a58cd2f4e412795747759f5ad06216fa85b6d14000000006b483045022100f901a927fe30745d3cb698ddcdd4f94f1095e63b6e4c17285f829a419814d2cf02205454611b1732f85fee2b23b33c5e945631007a64927add34dcd27e397c7d19960121021809e241a90164f80a79fe8af7f218a123abd7c4632106968c560057187dab36ffffffff0210270000000000001976a91433f110b6ff611bf5f719927367dc36df255af74088ace4700000000000001976a914094809350f056628fd9e0011e45253f2033921fc88ac0000000000";
//            }

            List<CoinWallet> coinWallets = WalletApp.queryCurrrentWallet();

            if (!ToolUtils.isListEmpty(coinWallets)) {
                wallet = coinWallets.get(walletId);
            }

            if (wallet == null) {
                //终止后面全部程序的进行
                ToastUtils.showToast("Warn:当前钱包为空!");
                return;
            }
        }

        transactionEncode = encode(transaction);
        // 注意这里length的单位是 "字符"
        // 1个汉字=1个字符=2个字节(byte)
        // 1个字母=1个字符 = 1个字节？？？
        Logger.ds("压缩后：" + transactionEncode.length());
        Logger.ds("TransactionActivity 对签名Encode: " + transactionEncode);
        //签名code的字节长度
        infoSize = transactionEncode.length();

        //分页总数，以200字节
        total = (int) Math.ceil(infoSize * 1.0 / BYTE_PER_PAGE);
        //当前所在页数的索引
        index = 0;

        if (total > 1) {
            tvIndex.setTextColor(getResources().getColor(R.color.special_text));
        }

        //扩充可点击区域
        expandViewTouchDelegate();

        //默认生成二维码界面
        generateQrCode();
    }


    private void expandViewTouchDelegate() {
        UIHelper.expandViewTouchDelegate(iv_qr_sub, 10, 10, 10, 10);
        UIHelper.expandViewTouchDelegate(iv_qr_add, 10, 10, 10, 10);
        UIHelper.expandViewTouchDelegate(tv_last_page, 40, 40, 40, 40);
        UIHelper.expandViewTouchDelegate(tv_next_page, 40, 40, 40, 40);
    }


    @OnClick(R.id.btn_back)
    void back() {
        finish();
    }


    private void generateQrCode() {
        isOk = false;
        current = "0%";
        isFirst = true;

        //生成交易二维码
        ThreadPoolManager.execute(runnable);
    }


    @OnClick(R.id.tv_last_page)
    void lastPage() {
        if (isOk("正在生成...")) return;

        --index;
        if (index < 0) {
            index = 0;
            return;
        }

        changeTextColor();

        updateInfo(index);
    }


    @OnClick(R.id.tv_next_page)
    void nextPage() {
        if (isOk("正在生成...")) return;

        ++index;
        if (index > total - 1) {
            index = total - 1;
            return;
        }

        changeTextColor();

        updateInfo(index);
    }


    @OnClick(R.id.iv_qr_sub)
    void sub() {
        if (isOk("正在生成...")) return;

        --total;
        if (total < 1) {
            total = 1;
        }

        changeTextColor();

        //减1页，再次生成
        generateQrCode();
    }


    @OnClick(R.id.iv_qr_add)
    void add() {
        if (isOk("正在生成...")) return;

        ++total;
        if (total > infoSize) {
            total = infoSize;
        }

        changeTextColor();

        //加1页，再次生成
        generateQrCode();
    }


    //根据当前索引，变色上一页和下一页按钮
    private void changeTextColor() {
        if (index == 0) {
            tv_last_page.setTextColor(getResources().getColor(R.color.special_text2));
            ivPageUp.setVisibility(View.GONE);
        } else {
            tv_last_page.setTextColor(getResources().getColor(R.color.special_text));
            ivPageUp.setVisibility(View.VISIBLE);
        }

        if (index + 1 < total) {
            tv_next_page.setTextColor(getResources().getColor(R.color.special_text));
            ivPageDown.setVisibility(View.VISIBLE);
        } else {
            tv_next_page.setTextColor(getResources().getColor(R.color.special_text2));
            ivPageDown.setVisibility(View.GONE);
        }
    }


    //转化成二维码数据
    public String encode(String transaction) {
        JSONObject root = new JSONObject();
        try {
            root.put("a", wallet.getAddress());
            root.put("t", wallet.getType());
            root.put("s", transaction);
        } catch (Exception e) {
            return "";
        }
        String rawText = root.toString();
        Logger.ds("压缩前：" + rawText.length());
        return LZW.encrypt(rawText);
        //return Base64.encodeToString(rawText.getBytes(), 2);
    }


    //取消AsyncTask的使用，避免内存泄漏
    Runnable runnable = new Runnable() {
        @Override
        public void run() {

            Logger.ds("> 生成交易二维码-encode: " + transactionEncode);
            //每次new都重置数组了
            //生成total数量的二维码
            bitmaps = new Bitmap[total];

            //每一页所承载的数据量(换成索引就是最后1个index)
            int lenPerPart = (int) Math.ceil(infoSize * 1.0 / total);
            int startPos = 0;
            int off = 0;

            try {
                for (int i = 0; i < total; ++i) {

                    if (startPos + lenPerPart > infoSize) {
                        off = infoSize - startPos;
                    } else {
                        off = lenPerPart;
                    }

                    JSONObject obj = new JSONObject();

                    /*if (i == 0) {
                        obj.put("id", WalletApp.queryCurrrentAccountId());
                    }
                    if (total > 1) {
                        obj.put("i", i);
                        obj.put("n", total);
                    }*/

                    //现在要求每页都补全属性了
                    obj.put("id", WalletApp.queryCurrrentAccountId());
                    obj.put("i", i);
                    obj.put("n", total);
                    obj.put("t", 1);

                    //  *每一页的数据量 
                    String slice = transactionEncode.substring(startPos, startPos + off);
                    Logger.ds(">>\t" + "index:" + i + " value:" + slice);
                    obj.put("d", slice);

                    //这个表示开始的位置在之前片段的末尾
                    startPos = startPos + off;

                    //当前所拼接的内容
                    String qrStr = obj.toString();

                    //当前所拼接的内容转成二维码
                    bitmaps[i] = QRCodeEncoder.syncEncodeQRCode(qrStr, BGAQRCodeUtil.dp2px(TransactionActivity.this, 240));

                    //当前生成的百分比
                    float percent = (float) (((i + 1) * 1.0) / total) * 100;
                    current = String.format("%.2f", percent) + "%";

                    if (isFirst) {
                        //全部生成完毕则及时刷新当前界面
                        handler.sendEmptyMessage(0);
                    }
                }

                if (!isFirst) {
                    current = "100%";
                    //全部生成完毕则及时刷新当前界面
                    handler.sendEmptyMessage(0);
                }

            } catch (Exception e) {
                //重置
                isOk = true;
                current = "0%";
                Logger.ds("生成交易二维码失败: " + e.getMessage());
            }

        }
    };


    WeakHandler handler = new WeakHandler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //MainThreadUI
                    index = 0;
                    if (bitmaps[0] != null) {
                        ivQrCode.setVisibility(View.VISIBLE);
                        updateInfo(0);
                        changeTextColor();

                        if (!isFirst) {
                            //可以点了
                            isOk = true;

                        } else {
                            if (total == 1) {
                                isOk = true;
                            }
                        }

                        if (isFirst) {
                            //经历过第一次后则重置
                            isFirst = false;
                        }

                    } else {
                        //重置
                        isOk = true;
                        current = "0%";
                        Toast.makeText(TransactionActivity.this, "生成二维码失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }

            //需要继续处理就返回false，默认false
            return true;
        }
    });


    private boolean isOk(String tip) {
        if (!isOk) {
            //没有OK就不能点呗
            ToastUtils.showToast(tip + "\t" + current);
            return true;
        }
        return false;
    }


    private void updateInfo(int index) {
        //刷新二维码，关键点是bitmaps这个数组
        ivQrCode.setImageBitmap(bitmaps[index]);
        //边缘的颜色
        //cvQrCode.setBackgroundColor(getResources().getColor(R.color.transparent));
        //刷新索引号
        tvIndex.setText((index + 1) + "/" + total);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                StartX = event.getX();
                break;
            case MotionEvent.ACTION_UP:
                if (event.getX() > StartX) {
                    //上一页
                    lastPage();
                } else if (event.getX() < StartX) {
                    //下一页
                    nextPage();
                }
                break;
        }

        return super.onTouchEvent(event);
    }


    @OnClick({R.id.iv_page_up, R.id.iv_page_down, R.id.btn_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_page_up:
                //上一页
                lastPage();
                break;
            case R.id.iv_page_down:
                //下一页
                nextPage();
                break;
            case R.id.btn_confirm:
                //弹出确认更新的弹窗
                String title = StringUtil.getResourceString(R.string.universal_title_transaction_is_ok);
                String content = StringUtil.getResourceString(R.string.universal_content_transaction_is_ok);
                UniversalDialog.showSingeleTipDialog(getSupportFragmentManager(), this, title, content);
                break;
        }
    }


    @Override
    public void onItemClick(String... texts) {
        //在这里写本地更新余额的操作
        ToastUtils.showToast("本地更新余额-待续");
    }


}
